$(function() {
    var adModel = Backbone.Model.extend({
        urlRoot : function() {
            var appId = getUrlParam("id");
            
            if(debug){
                return "interface.json";
            }else{
                return interfaceRoot + "/api/" + appId + "/ads";
            }
            
        },
        defaults : function() {
            return {
                appId : "",
                order : myAds.nextOrder(),
                name : "",
                form : "",
                type : "",
                origin : "",
                startTime : "",
                endTime : "",
                displayType : "",
                text : "",
                imgUrl : "",
                clickType : "",
                adUrl : "",
                remark : "",
                status : ""
            };
        },
        initialize : function() {
            for(var key in this.defaults()) {
                if(key == "order")
                    continue;
                if(!this.get(key)) {
                    this.set({
                        key : this.defaults().key
                    });
                }
            }
        },
        parse : function(data) {//fetch,save 触发

            if(data.startTime) {
                var startTime = new Date(data.startTime);
                var endTime = new Date(data.endTime);
                data.startTime = startTime.Format("yyyy-MM-dd hh:mm");
                data.endTime = endTime.Format("yyyy-MM-dd hh:mm");              
                
            }

            console.log(data);
            return data;
        }
    });

    var adList = Backbone.Collection.extend({
        model : adModel,
        url : function() {
            var appId = getUrlParam("id");

            if(debug){
                return "getAds.json";
            }else{
                return interfaceRoot + "/api/apps/" + appId + "/ads";
            }
            
        },
        nextOrder : function() {
            if(!this.length)
                return 1;
            return this.last().get('order') + 1;
        },
        parse : function(data) {
            if(data.err) {// 出错
                return;
            }

            // 'data' contains the raw JSON object
            console.log(data);
            return data;
        },
        count : function() {
            return this.length;
        },
        comparator : function(ad) {
            return ad.get('order');
        }
    });

    var trView = Backbone.View.extend({
        tagName : "tr",

        template : _.template($('#adTable_tr_template').html()),

        events : {
            "click .edit" : "edit",
            "click .offline" : "offline",
            "click .online" : "online",
            "click .delete" : "confirmDelete"
        },

        initialize : function() {
            this.listenTo(this.model, 'change', this.render);
            this.listenTo(this.model, 'destroy', this.remove);
        },

        render : function() {
            this.$el.html(this.template(this.model.toJSON()));
            return this;
        },

        edit : function() {
            //click .edit button
            //TO DO
            var appId = getUrlParam("id");
            var appName = getUrlParam("name");
            var appPlatform = getUrlParam("platform");
            var adid = this.model.get("id");
            

            var url = "editAd.html?appid=" + appId + "&adid=" + adid + "&name=" + appName + "&platform=" + appPlatform;
            window.location = window.encodeURI(url);            
        },
        offline : function() {

        },

        online : function() {

        },
        confirmDelete : function() {
            //click .delete button
            //TO DO
            var model = this.model;
            $("#deleteConfirmModal").modal();
            $("#deleteConfirmModal .btn-primary").unbind();
            $("#deleteConfirmModal .btn-primary").click(function() {
                model.destroy();
                $("#deleteConfirmModal").modal("hide");
            })
        }
    });

    var appView = Backbone.View.extend({
        el : $("#container"),

        template : _.template($('#stats-template').html()),

        events : {
            "click #online" : "fetchOnline",
            "click #readyToOnline" : "fetchReadyToOnline",
            "click #offline" : "fetchOffline",

            "click #addAdButton" : "addAdModal",
            "click #adjustButton" : "adjust",
            "click #selectAdTypeModal .modal-footer .btn-primary" : "addAd",
        },

        initialize : function() {//在这里初始化整个应用
            var appName = getUrlParam("name");
            var appPlatform = getUrlParam("platform");
            var appid = getUrlParam("id");

            //改变导航栏名称
            $("#container .span9 .breadcrumb .active").text(appName + "  " + appPlatform);

            this.listenTo(myAds, 'add', this.addOne);
            this.listenTo(myAds, 'reset', this.addAll);
            this.listenTo(myAds, 'all', this.render);

            myAds.fetch({
                data : {
                    appid : appid,
                    status : "在线中"
                }
            });
        },

        render : function() {
            var count = myAds.count();

            this.$("#stats").html($.trim(this.template({
                count : count
            })));

        },
        fetchOnline : function() {
            this.$("#myNav .active").removeClass("active");
            this.$("#myNav li:eq(0)").addClass("active");
            var appid = getUrlParam("id");

            myAds.fetch({
                data : {
                    appid : appid,
                    status : "在线中"
                }
            });
        },

        fetchReadyToOnline : function() {
            this.$("#myNav .active").removeClass("active");
            this.$("#myNav li:eq(1)").addClass("active");
            var appid = getUrlParam("id");

            myAds.fetch({
                data : {
                    appid : appid,
                    status : "待上线"
                }
            });
        },

        fetchOffline : function() {
            this.$("#myNav .active").removeClass("active");
            this.$("#myNav li:eq(2)").addClass("active");
            var appid = getUrlParam("id");

            myAds.fetch({
                data : {
                    appid : appid,
                    status : "已下线"
                }
            });
        },

        addAdModal : function() {
            $('#selectAdTypeModal').modal()
        },

        adjust : function() {

        },

        addAd : function() {
            var $modal = $('#selectAdTypeModal');
            var form = $.trim($('#selectAdTypeModal button.active').text());

            var appName = getUrlParam("name");
            var appPlatform = getUrlParam("platform");
            var appid = getUrlParam("id");
            var adOrder = myAds.nextOrder();

            var url = "addAd.html?id=" + appid + "&name=" + appName + "&platform=" + appPlatform + "&form=" + form + "&order=" + adOrder;
            window.location = window.encodeURI(url);

        },

        addOne : function(ad) {
            var view = new trView({
                model : ad
            });
            this.$("#adTable tbody").append(view.render().el);
        },
        addAll : function() {
            myAds.each(this.addOne, this);
        }
    });

    var myAds = new adList;

    var myAppView = new appView;

    $("#button2").click(function() {
        console.log(JSON.stringify(myAds.toJSON()))
    })
})

